require 'digest/sha1' # this is what gets used for authentication

class User < ActiveRecord::Base
  has_one :address, :foreign_key => "user_id", :dependent => :destroy
  
  USER_ROLES = [
    # Label       Value in db
    ["Customer",    "cust"],
    ["Administrator",  "admin"]
    ]
  
  validates_inclusion_of :user_role, :in => USER_ROLES.map {|disp, value| value}
  
  validates_presence_of	:name, :firstName, :nickName, :user_role, :email
    
  validates_uniqueness_of :nickName
  
  attr_accessor :confirm_password 
  validates_confirmation_of :password
  validate :password_non_blank 
  
  validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
  
  # this is for when we fill out address for a new user.  It allows you to nest a new address object in a new user form.
  accepts_nested_attributes_for :address 

  def isAdmin?
    if self.user_role == "admin"
      return true
    else
      return false
    end
  end
  
  def self.isLoggedIn?
    if User.find_by_id(session[:user_id])
      return true
    else
      return false
    end
  end
  
  #this is how logging in works.
  def self.authenticate(name, password) 
    user = self.find_by_nickName(name) 
    if user
      expected_password = encrypted_password(password, user.salt)
	  if user.hashed_password != expected_password
        user = nil 
      end
    end
    user
  end
  
  def password 
    @password
  end
  
  def password=(pwd) 
    @password = pwd 
    return if pwd.blank? 
    create_new_salt 
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  # This is a callback from ActiveRecord.  If you need to do something after sql destroys a record, you override these various callbacks depending on what point you need to override what happens.
  def after_destroy 
    if User.count.zero?
      raise "Can't delete last user"
    end 
  end
  
  private
  def password_non_blank 
    errors.add(:password, "Missing password") if hashed_password.blank?
  end
  
  def create_new_salt 
    self.salt = self.object_id.to_s + rand.to_s
  end
  
  #This was a recommended way to encrypt passwords from the book Agile Web Development with Rails, 3rd Edition, Sam Ruby, Dave Thomas, and David Heinemeier Hansson.  Published by The Pragmatic Bookshelf 
  def self.encrypted_password(password, salt) 
    string_to_hash = password + "wibble" + salt 
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
end




# == Schema Information
#
# Table name: users
#
#  id              :integer         not null, primary key
#  name            :string(255)
#  firstName       :string(255)
#  hashed_password :string(255)
#  nickName        :string(255)
#  created_at      :datetime
#  updated_at      :datetime
#  salt            :string(255)
#  user_role       :string(255)
#

